﻿namespace AntdUI_HamburgerMenuTabs.Uc
{
    /// <summary>
    /// 汉堡包菜单 + 多标签页面
    /// </summary>
    public partial class HamburgerMenuTabs : UserControl
    {
        public HamburgerMenuTabs()
        {
            InitializeComponent();

            Load += (s, e) =>
            {
                // 加载菜单折叠/展开状态（用户控件首次显示之后调用，否则宽度计算有问题）
                LoadMenuCollapseStatus();
            };

            panelMenu.Shadow = 5;
            panelMenu.ShadowOpacityAnimation = true;
            panelMenu.ShadowOpacity = 0.2F;
            panelMenu.ShadowOpacityHover = 0.8F;

            panelTabs.Shadow = 5;
            panelTabs.ShadowOpacityAnimation = true;
            panelTabs.ShadowOpacity = 0.2F;
            panelTabs.ShadowOpacityHover = 0.8F;

            tabs1.TypExceed = AntdUI.TabTypExceed.Button;

            InitMenu();
        }

        /// <summary>
        /// 设置菜单项
        /// </summary>
        /// <param name="menus"></param>
        public void SetMenu(List<Models.MenuItem>? menus)
        {
            hm1.SetMenu(menus);
        }

        /// <summary>
        /// 手风琴模式：true 每次只能展开一个菜单项；false 可以同时展开多个菜单项
        /// </summary>
        /// <param name="isAccordion"></param>
        public void SetAccordion(bool isAccordion)
        {
            hm1.IsAccordion = isAccordion;
        }

        /// <summary>
        /// MenuItem 选择模式：0=默认，会触发选中页面；1=程序控制菜单选中，不触发选中页面；
        /// </summary>
        private int menuSelectMode = 0;

        /// <summary>
        /// 初始化菜单
        /// </summary>
        private void InitMenu()
        {
            SetMenu(null);

            hm1.SetSplitterMenu(splitter1);

            hm1.Menu.SelectChanged += (s, e) =>
            {
                var item = e.Value;

                if (menuSelectMode == 0)
                {
                    if (item.Tag is Models.MenuItemTag tag)
                    {
                        string title = $"{item.Text}";
                        string path = $"{tag.Path}";
                        string path2 = $"{tag.Path2}";
                        Type? pageType = tag.PageType;
                        string? svg = item.IconSvg;
                        bool closeable = tag.Closeable;

                        LoadTabPage(title, path, path2, pageType, svg, closeable);

                        Properties.Settings.Default.LastMenuPath = path;
                        Properties.Settings.Default.Save();
                    }
                }
            };

            tabs1.ClosingPage += (s, e) =>
            {
                DisposePage(e.Value);
                return true;
            };

            // 手动切换页面后定位菜单项
            tabs1.SelectedIndexChanged += (s, e) =>
            {
                if (tabPageSelectMode == 0)
                {
                    MenuLocateAfterTabPageSelected();
                }
            };

            #region 右键菜单

            AntdUI.IContextMenuStripItem[] cMenu1 = [
                new AntdUI.ContextMenuStripItem("关闭所有页面")
                {
                    IconSvg = "CloseCircleOutlined",
                },
                new AntdUI.ContextMenuStripItem("关闭其它页面")
                {
                    IconSvg = "CloseCircleFilled",
                },
            ];

            tabs1.Click += (s, e) =>
            {
                if (e is MouseEventArgs me && me.Button == MouseButtons.Right)
                {
                    AntdUI.ContextMenuStrip.open(this, it =>
                    {
                        switch (it.Text)
                        {
                            case "关闭所有页面":
                                CloseAllPages();
                                break;
                            case "关闭其它页面":
                                var page = tabs1.SelectedTab;
                                if (page != null && page.Tag is Models.TabPageTag tag)
                                {
                                    var path = tag.MenuPath;
                                    if (!string.IsNullOrEmpty(path)) CloseOrtherPages(path);
                                }
                                break;
                        }
                    }, cMenu1);
                }
            };

            #endregion
        }

        /// <summary>
        /// TabPage 选择模式：0=默认；1=自定义程序控制；
        /// </summary>
        int tabPageSelectMode = 0;

        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="title"></param>
        /// <param name="path"></param>
        /// <param name="path2"></param>
        /// <param name="pageType"></param>
        private void LoadTabPage(string title, string path, string path2, Type? pageType, string? svg, bool closeable)
        {
            tabPageSelectMode = 1;

            bool findInstance = false;

            foreach (AntdUI.TabPage _page in tabs1.Pages)
            {
                if (_page.Tag is Models.TabPageTag tag)
                {
                    if (string.Equals(tag.MenuPath, path, StringComparison.OrdinalIgnoreCase))
                    {
                        tabs1.SelectedTab = _page;
                        findInstance = true;
                        break;
                    }
                }
            }

            if (!findInstance)
            {
                AntdUI.TabPage page = new()
                {
                    Text = title,
                    IconSvg = svg,
                    Tag = new Models.TabPageTag(path) { Closeable = closeable },
                };
                if (!closeable)
                {
                    page.ReadOnly = true;
                }
                page.Disposed += (s, e) =>
                {
                    if (ParentForm != null)
                    {
                        AntdUI.Message.info(ParentForm, $"页面【{page.Text}】已关闭。");
                    }
                };

                AntdUI.Panel panelContent = new()
                {
                    Dock = DockStyle.Fill,
                };

                AntdUI.Panel panelPage = new()
                {
                    Dock = DockStyle.Fill,
                    Padding = new(5),
                };

                panelPage.Controls.Add(panelContent);
                page.Controls.Add(panelPage);

                if (pageType != null)
                {
                    object[] args = [title, path, path2];
                    UserControl pageContent;
                    try
                    {
                        pageContent = (UserControl)Activator.CreateInstance(pageType, args)!;
                    }
                    catch
                    {
                        pageContent = (UserControl)Activator.CreateInstance(pageType)!;
                    }
                    pageContent.Dock = DockStyle.Fill;
                    panelContent.Controls.Add(pageContent);
                }
                else
                {
                    var alert = new AntdUI.Alert()
                    {
                        TextTitle = "警告",
                        Text = "菜单未配置关联页面！",
                        Icon = AntdUI.TType.Warn,
                        Height = 100,
                        Dock = DockStyle.Top,
                    };
                    panelContent.Padding = new(10);
                    panelContent.Controls.Add(alert);
                }

                tabs1.Pages.Add(page);
                tabs1.SelectedTab = page;
            }

            tabPageSelectMode = 0;
        }

        /// <summary>
        /// 释放页面资源
        /// </summary>
        /// <param name="page"></param>
        public static void DisposePage(AntdUI.TabPage page)
        {
            if (page.Controls.Count > 0)
            {
                if (page.Controls[0] is AntdUI.Panel panelPage)
                {
                    if (panelPage.Controls.Count > 0)
                    {
                        if (panelPage.Controls[0] is AntdUI.Panel panelContent)
                        {
                            if (panelContent.Controls.Count > 0)
                            {
                                if (panelContent.Controls[0] is UserControl uc)
                                {
                                    // 释放页面资源
                                    uc.Dispose();
                                    panelContent.Dispose();
                                    panelPage.Dispose();
                                }
                            }
                        }
                    }
                }
            }
        }

        public AntdUI.Panel? GetPanelPage()
        {
            if (tabs1.SelectedTab != null)
            {
                var page = tabs1.SelectedTab;
                if (page.Controls.Count > 0)
                {
                    if (page.Controls[0] is AntdUI.Panel panel) return panel;
                }
            }
            return null;
        }

        /// <summary>
        /// 点击多标签选项卡切换页面后定位选中菜单项
        /// </summary>
        private void MenuLocateAfterTabPageSelected()
        {
            AntdUI.TabPage? page = tabs1.SelectedTab;

            if (page != null)
            {
                if (page.Tag is Models.TabPageTag tag)
                {
                    hm1.MenuItemCollapsedAll(null);
                    menuSelectMode = 1;
                    hm1.MenuItemSelectOne($"{tag.MenuPath}");
                    menuSelectMode = 0;
                }
            }
        }

        /// <summary>
        /// 菜单默认选中项
        /// </summary>
        public void MenuSelectDefault()
        {
            hm1.Menu.SelectIndex(0, true);
        }

        /// <summary>
        /// 选中最后一次访问的菜单项并打开页面
        /// </summary>
        /// <returns></returns>
        public bool MenuSelectLast(Control? content = null)
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastMenuPath))
            {
                try
                {
                    hm1.MenuItemCollapsedAll(null);

                    if (content != null) menuSelectMode = 1;

                    hm1.MenuItemSelectOne($"{Properties.Settings.Default.LastMenuPath}");

                    if (content != null)
                    {
                        var panelPage = GetPanelPage();
                        panelPage?.Controls.Add(content);
                    }

                    return true;
                }
                finally
                {
                    menuSelectMode = 0;
                }
            }
            return false;
        }

        /// <summary>
        /// 加载菜单面板折叠/展开状态
        /// </summary>
        public void LoadMenuCollapseStatus()
        {
            hm1.LoadMenuCollapseStatus();
        }

        /// <summary>
        /// 关闭所有页面
        /// </summary>
        public void CloseAllPages()
        {
            while (tabs1.Pages.Count > 0)
            {
                var page = tabs1.Pages[0];
                DisposePage(page);
                tabs1.Pages.Remove(page);
            }
        }

        /// <summary>
        /// 关闭其它页面
        /// </summary>
        /// <param name="path"></param>
        public void CloseOrtherPages(string path)
        {
            List<AntdUI.TabPage> pages = [.. tabs1.Pages];

            foreach (var page in pages)
            {
                if (page.Tag is Models.TabPageTag tag)
                {
                    if (tag.MenuPath != path)
                    {
                        DisposePage(page);
                        tabs1.Pages.Remove(page);
                    }
                }
            }

            pages.Clear();
        }
    }
}